package me.king.mybatis.component.biz;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class ServiceHandler implements InvocationHandler {
	
	private BaseServiceTemplate<?> template;
	private static SqlSessionFactory factory;
	
	static {
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			factory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ServiceHandler(BaseServiceTemplate<?> baseServiceTemplate) {
		this.template = baseServiceTemplate;
	}



	public BaseServiceTemplate<?> getTemplate() {
		return template;
	}



	public void setTemplate(BaseServiceTemplate<?> template) {
		this.template = template;
	}



	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		SqlSession session = factory.openSession();
		template.setSession(session);
		Object res = method.invoke(template, args);
		if (!method.getName().equals("getSession")) {
			session.commit();
			session.close();
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public <T>IBaseService<T> getProxy() {
		return (IBaseService<T>)Proxy.newProxyInstance(template.getClass().getClassLoader(), 
				template.getClass().getInterfaces(), this);
	}

}
